package com.zyzg.config;

import com.zyzg.config.properties.RabbitMqProperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;


@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "spring.rabbitmq")
public class RabbitMQConfig {
    private RabbitMqProperties business = new RabbitMqProperties();

    @Bean(name = "businessConnectionFactory")
    @Primary
    public ConnectionFactory businessConnectionFactory() {
        return createConnectionFactory(business);
    }

    @Bean(name = "businessRabbitTemplate")
    @Primary
    public RabbitTemplate
    businessRabbitTemplate(@Qualifier("businessConnectionFactory") ConnectionFactory connectionFactory) {
        RabbitTemplate businessRabbitTemplate = new RabbitTemplate(connectionFactory);
        return businessRabbitTemplate;
    }

    private ConnectionFactory createConnectionFactory(RabbitMqProperties rabbitMqProperties) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(rabbitMqProperties.getHost());
        connectionFactory.setPort(rabbitMqProperties.getPort());
        connectionFactory.setUsername(rabbitMqProperties.getUsername());
        connectionFactory.setPassword(rabbitMqProperties.getPassword());
        connectionFactory.setVirtualHost(rabbitMqProperties.getVirtualHost());
        return connectionFactory;
    }

    /**
     * 消费工厂类创建
     *
     * @param connectionFactory
     * @return {@link SimpleRabbitListenerContainerFactory}
     */
    @Bean(name = "businessContainerFactory")
    public SimpleRabbitListenerContainerFactory
    businessConnectionFactory(@Qualifier("businessConnectionFactory") ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        // 设置并发消费者数量
        factory.setConcurrentConsumers(10);
        factory.setMaxConcurrentConsumers(20);

        // 设置预取计数
        factory.setPrefetchCount(200);
//        factory.setAcknowledgeMode(AcknowledgeMode.NONE);
        // 设置消息确认模式为手动确认
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }

}